package com.example.pagingdemo.api;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author: tuyrt7 on 2020/9/9.
 */
public class RetrofitClient {

    private static RetrofitClient mRetrofitClient;

    private Retrofit mRetrofit;

    private RetrofitClient() {
    }

    public static synchronized RetrofitClient get() {
        if (mRetrofitClient == null) {
            mRetrofitClient = new RetrofitClient();
        }
        return mRetrofitClient;
    }

    public Api buildApi(String baseUrl) {
        mRetrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(getClient())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return mRetrofit.create(Api.class);
    }

    private OkHttpClient getClient() {
        OkHttpClient.Builder mBuilder = new OkHttpClient.Builder()
                /*.addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request original = chain.request();
                        HttpUrl originalHttpUrl = original.url();
                        HttpUrl newHttpUrl = originalHttpUrl.newBuilder()
                                .addQueryParameter("apikey", Api.API_KEY)
                                .build();
                        Request newRequest = original.newBuilder().url(newHttpUrl).build();
                        return chain.proceed(newRequest);
                    }
                })*/;
        return mBuilder.build();
    }
}
